package com.next

import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.NOT_FOUND

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_COMPANY_ADMINISTRATOR', 'ROLE_COMPANY_USER'])
@Transactional(readOnly = true)
class OpportunityTeamController
{

    def springSecurityService
    def exportService
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def opportunityTeamList = OpportunityTeam.findAll("from OpportunityTeam where user.username = '${username}' order by modifiedDate desc", [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = OpportunityTeam.executeQuery("select count(id) from OpportunityTeam where user.username = '${username}'")

        respond opportunityTeamList, model: [opportunityTeamCount: count[0]]
    }

    // def show(Opportunity opportunity)
    // {
    //     def history
    //     if (opportunity && opportunity?.serialNumber)
    //     {
    //         history = OpportunityHistory.findAll("from OpportunityHistory as o where o.serialNumber = '${opportunity.serialNumber}' order by modifiedDate desc")
    //     }
    //     def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)
    //     def opportunityRoles = OpportunityRole.findAllByOpportunity(opportunity)
    //     def opportunityNotifications = OpportunityNotification.findAllByOpportunity(opportunity)
    //     def opportunityFlows = OpportunityFlow.findAll("from OpportunityFlow where opportunity.id = ${opportunity?.id} order by executionSequence ASC")
    //     def creditReport = CreditReport.findAllByOpportunity(opportunity)
    //     def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
    //     //        def liquidityRiskReport = LiquidityRiskReport.findAll("from LiquidityRiskReport where opportunity.id = " + "${opportunity?.id} order by createdDate ASC")
    //     def activities = Activity.findAllByOpportunity(opportunity)
    //     def currentProgress = OpportunityFlow.countByOpportunityAndStageLessThanEquals(opportunity, opportunity?.stage) * 100
    //     def totalProgress = OpportunityFlow.countByOpportunity(opportunity)
    //     def progressPercent
    //     if (totalProgress > 0)
    //     {
    //         progressPercent = currentProgress / totalProgress
    //     }
    //     else
    //     {
    //         progressPercent = 0
    //     }
    //     respond opportunity, model: [history: history, opportunityTeams: opportunityTeams, opportunityRoles: opportunityRoles, opportunityNotifications: opportunityNotifications, opportunityFlows: opportunityFlows,
    //         creditReport: creditReport, opportunityContacts: opportunityContacts,
    //         activities: activities, progressPercent: progressPercent]
    // }

    def create()
    {
        def opportunity = Opportunity.findById(params["opportunity"])
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        TeamRole editTeamRole = TeamRole.findByName('Edit')
        def team = OpportunityTeam.findByOpportunityAndUser(opportunity, user)

        if (opportunity?.user?.id == user?.id || team?.teamRole?.id == editTeamRole?.id)
        {
            def opportunityTeam = OpportunityTeam.findAllByOpportunity(opportunity)
            def userList
            if (opportunityTeam?.size() > 0)
            {
                def sqlStr = "("
                opportunityTeam.each {
                    sqlStr += it.user.id + ","
                }
                sqlStr = sqlStr.substring(0, sqlStr.lastIndexOf(',')) + ")"
                userList = User.findAll("from User as u where u.id not in ${sqlStr}")
            }
            else
            {
                userList = User.list()
            }
            respond new OpportunityTeam(params), model: [userList: userList, opportunity: opportunity]
        }
        else
        {
            flash.message = "没有创建权限"
            redirect controller: "opportunity", action: "show", id: opportunity?.id
            // respond opportunity, view: 'show'
        }
    }

    @Transactional
    def save(OpportunityTeam opportunityTeam)
    {
        def userList = User.list()
        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunityTeam?.opportunity)
        opportunityTeams?.each {
            userList -= it?.user
        }

        if (opportunityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunityTeam.hasErrors())
        {
            //COMMENT THE INFO THEN YOU WILL SEE MIRACLES
            log.info "userList:" + userList

            transactionStatus.setRollbackOnly()
            respond opportunityTeam.errors, view: 'create', model: [opportunity: opportunityTeam?.opportunity, userList: userList]
            return
        }

        opportunityTeam.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: '', args: [message(code: 'opportunityTeam.label', default: 'OpportunityTeam'), opportunityTeam.id])
                // redirect(action: "show", id: opportunityTeam.opportunity.id)
                redirect(controller: "opportunity", action: "show", params: [id: opportunityTeam.opportunity.id])
            }
            '*' { respond opportunityTeam, [status: CREATED] }
        }
    }

    def edit(OpportunityTeam opportunityTeam)
    {
        def username = springSecurityService?.getPrincipal()?.username
        def user = User.findByUsername(username)

        TeamRole editTeamRole = TeamRole.findByName('Edit')
        OpportunityTeam currentOpportunityTeam = OpportunityTeam.findByOpportunityAndUser(opportunityTeam.opportunity, user)

        if (opportunityTeam.opportunity.user.id == user.id || currentOpportunityTeam?.teamPermission?.id == editTeamRole.id)
        {
            respond opportunityTeam, model: [user: user]
        }
        else
        {
            flash.message = "没有编辑权限"
            redirect controller: "opportunity", action: "show", id: opportunityTeam.opportunity.id
        }
    }

    @Transactional
    def update(OpportunityTeam opportunityTeam)
    {
        if (opportunityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunityTeam.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunityTeam.errors, view: 'edit'
            return
        }
        opportunityTeam.save flush: true

        // redirect opportunityTeam
        redirect(controller: "opportunity", action: "show", params: [id: opportunityTeam?.opportunity?.id])
    }

    @Transactional
    def delete(OpportunityTeam opportunityTeam)
    {
        if (opportunityTeam == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }


        opportunityTeam.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'opportunityTeam.label', default: 'OpportunityTeam'), opportunityTeam.id])
                // redirect action: "index", method: "GET"
                redirect(controller: "opportunity", action: "show", params: [id: opportunityTeam?.opportunity?.id])
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'opportunityTeam' + '.label', default: 'OpportunityTeam'),
                    params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchOpportunityTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username

        String sql = "from OpportunityTeam as o where 1 = 1 and o.user.username = '${username}'"
        def accountName = params['accountName']
        def ownerFullName = params['ownerFullName']
        if (accountName)
        {
            sql += " and o.opportunity.account.name like '%${accountName}%'"
        }
        if (ownerFullName)
        {
            sql += " and o.opportunity.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(o.id) " + sql
        sql += ' order by o.createdDate desc'

        def list = OpportunityTeam.findAll(sql, [max: params.max ?: 10, offset: params.offset ?: 0])
        def count = OpportunityTeam.executeQuery(countSql)
        respond list, model: [opportunityTeamCount: count[0], params: params], view: 'index'
    }

    def exportOpportunityTeam()
    {
        def username = springSecurityService?.getPrincipal()?.username

        String sql = "from OpportunityTeam as o where 1 = 1 and o.user.username = '${username}'"

        def ownerFullName = params['ownerFullName']
        if (ownerFullName)
        {
            sql += " and o.opportunity.user.fullName like '%${ownerFullName}%'"
        }

        String countSql = "select count(o.id) " + sql
        sql += ' order by o.createdDate desc'

        def list = OpportunityTeam.findAll(sql)
        def count = OpportunityTeam.executeQuery(countSql)

        if (params?.f && params.f != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.f]
            response.setHeader("Content-disposition", "attachment; filename=opportunityTeam.${params.extension}")
            List fields = ["opportunity.stage.name", "opportunity.type.name", "opportunity.probability", "opportunity.amount", "opportunity.account.name", "opportunity.productLine.name", "opportunity.product.name", "opportunity.purchasingMethod.name", "opportunity.startTime", "opportunity.endTime", "opportunity.source.name", "opportunity.status.name", "opportunity.causeOfFailure", "opportunity.descriptionOfFailure", "opportunity.createdDate", "opportunity.modifiedDate"]
            Map labels = ["opportunity.stage.name": "商机阶段", "opportunity.type.name": "商机类型", "opportunity.probability": "几率", "opportunity.amount": "金额", "opportunity.account.name": "客户", "opportunity.productLine.name": "产品线", "opportunity.product.name": "产品", "opportunity.purchasingMethod.name": "采购方法", "opportunity.startTime": "商机发现时间", "opportunity.endTime": "客户预计采购时间", "opportunity.source.name": "来源", "opportunity.status.name": "状态", "opportunity.causeOfFailure": "失败原因", "opportunity.descriptionOfFailure": "商机描述", "opportunity.createdDate": "创建时间", "opportunity.modifiedDate": "修改时间"]
            exportService.export(params.f, response.outputStream, list, fields, labels, [:], [:])
        }
    }
}
